﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;

namespace Sytem.Windows.Controls.WpfPropertyGrid.Metadata
{
    public class PropertyEditorOptionAttribute : Attribute
    {
        private Type target;
        private string[] parametres;
        public PropertyEditorOptionAttribute(Type typeTarget, params string[] parameters)
        {
            parametres = parameters;
            target = typeTarget;
        }

        internal void SetParameters(object p)
        {
            if (p == null)
                return;

            Type t = p.GetType();


            foreach (string item in parametres)
            {
                string[] tb = item.Split(':');
                string name = tb[0];
                string value = item.Substring(name.Length + 1);


                PropertyInfo prop = t.GetProperty(name);
                if (prop == null)
                    throw new Exception(string.Format("property {0} not found in {1}", name, p.GetType().Name));

                if (prop.PropertyType.IsEnum)
                {
                    string[] v1 = value.Split('.');
                    value = v1[v1.Length - 1];
                }


                var v = TypeDescriptor.GetConverter(prop.PropertyType).ConvertFromString(value);

                prop.SetValue(p, v, null);

            }

        }


        internal bool TargetValid(Type type)
        {
            return type == target;
        }
    }
}
